import { Component } from '@angular/core';
import { IonicPage, ViewController, ToastController } from 'ionic-angular';
import { HttphandleProvider } from '../../providers/httphandle/httphandle';
import { LocalstorageProvider } from '../../providers/localstorage/localstorage';
import { Brightness } from '@ionic-native/brightness';

/**
 * Generated class for the QrcodeshowPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-qrcodeshow',
  templateUrl: 'qrcodeshow.html',
})
export class QrcodeshowPage {
  private usercode: string
  private intervalId: number
  constructor(
    private viewCtrl: ViewController,
    private http: HttphandleProvider,
    private loc: LocalstorageProvider,
    private brightness: Brightness,
    private toastCtrl: ToastController
  ) {
    this.autoRefresh()
    // 关闭时 关闭定时器
    this.viewCtrl.onDidDismiss(() => {
      var defaultBrightness = this.loc.get('defaultBrightness')
      this.brightness.setBrightness(defaultBrightness);
      if (this.intervalId) {
        clearInterval(this.intervalId)
      }
    })
  }

  close(){
    this.viewCtrl.dismiss()
  }
  // 刷新code
  autoRefresh () {
    if (this.intervalId) {
      clearInterval(this.intervalId)
    }
    this.requestGetQrcode()
    this.intervalId = setInterval(() => {
      this.requestGetQrcode()
    },1000 * 60)
  }
  // 获取code
  requestGetQrcode () {
    this.http.get('/app/rest/v2/services/yes_CouponService/generateAuthCode').then(res => {
      this.usercode = res
    }).catch(err => {
      if (err.status == 401) {
        this.http.getToken((res) => {
          this.loc.set('token', res.json())
          this.requestGetQrcode()
        })
      } else {
        this.toastCtrl.create({
          message: err.errMsg || err,
          position: 'top',
          duration: 1000
        }).present();  
        console.log("服务器或网络", err)
      }
    })
  }

}
